package dao

import (
	"errors"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"miao-wails/backed/global"
	"miao-wails/backed/lib/db"
	"miao-wails/backed/structs/tables"
	"time"
)

var (
	DB    *gorm.DB
	IdpDb *gorm.DB
)

func InitDB() {
	var err error
	DB, err = db.GetDB(global.Conf.DB.Supper, global.Conf.DB.ShowSqlLog, global.Conf.DB.Source, global.Conf.DataDir)
	if err != nil {
		logrus.Errorf("连接数据库失败：%v", err)
	}
	autoMigrate()
}

func InitIdpDb() {
	var err error
	IdpDb, err = db.GetDB("sqlite", true, "miao.db", "C:\\VEIDP\\")
	if err != nil {
		logrus.Errorf("连接数据库失败：%v", err)
	}
}

func autoMigrate() {
	type vector[T any] []T
	var li = vector[interface{}]{
		&tables.SysConfig{},
		&tables.TarFile{},
		&tables.TarMusic{},
		&tables.SecretKey{},
		&tables.SecretText{},
		&tables.SecretChapter{},
	}
	for _, item := range li {
		if !DB.Migrator().HasTable(item) {
			err := DB.AutoMigrate(item)
			if err != nil {
				logrus.Errorf("初始化数据库表结构异常: %v", err)
			}
		}
	}
	var err error
	if err = initMusicTar(); err != nil {
		logrus.Errorf("initMusicTar 初始化配置时发生错误：[%v]", err)
	}
	if err = initPrivateSecret(); err != nil {
		logrus.Errorf("initPrivateSecret 初始化配置时发生错误：[%v]", err)
	}
	if err = initSecret(); err != nil {
		logrus.Errorf("initSecret 初始化配置时发生错误：[%v]", err)
	}
}
func initSecret() (err error) {
	var (
		m tables.SecretKey
	)
	err = DB.Model(&tables.SecretKey{}).Where("algorithm = ?", "simple").First(&m).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		m = tables.SecretKey{
			Id:        1,
			Title:     "明文",
			Remark:    "内容不加密",
			Algorithm: "simple",
			Content:   "",
			CreatedAt: time.Now().Unix(),
		}
		err = DB.Save(&m).Error
		if err != nil {
			return err
		}
	}
	return err
}

func initMusicTar() (err error) {
	var (
		li         []tables.SysConfig
		musicIdStr string
		loopStr    string
	)
	err = DB.Model(&tables.SysConfig{}).Where("key in ?", []string{tables.ConfigForCurrentMusicId, tables.ConfigForMusicLoopMode}).Find(&li).Error
	if err != nil {
		return
	}
	if len(li) == 0 {
		DB.Save(&tables.SysConfig{Key: tables.ConfigForCurrentMusicId, Val: "0"})
		DB.Save(&tables.SysConfig{Key: tables.ConfigForMusicLoopMode, Val: "loop"})
	}
	musicIdStr, err = loadConfig(tables.ConfigForCurrentMusicId)
	if err != nil {
		return err
	}
	global.Conf.ModuleConfig.MusicCurrentId = musicIdStr
	loopStr, err = loadConfig(tables.ConfigForMusicLoopMode)
	if err != nil {
		return err
	}
	global.Conf.ModuleConfig.MusicLoopMode = loopStr
	return
}

func initPrivateSecret() (err error) {
	var (
		priStr string
	)
	priStr, err = loadConfig(tables.ConfigForPrivateSecret)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = saveConfig(tables.ConfigForPrivateSecret, "999")
		if err != nil {
			return err
		}
	}
	priStr, err = loadConfig(tables.ConfigForPrivateSecret)
	if err != nil {
		return err
	}
	global.Conf.ModuleConfig.PrivateSecret = priStr
	return nil
}

// loadConfig 加载配置
func loadConfig(key string) (val string, err error) {
	var (
		m tables.SysConfig
	)
	err = DB.Model(&tables.SysConfig{}).Where("key = ?", key).First(&m).Error
	val = m.Val
	return
}

// saveConfig 保存更新配置
func saveConfig(key string, val string) (err error) {
	err = DB.Save(&tables.SysConfig{
		Key: key,
		Val: val,
	}).Error
	return
}
